import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Table, Spin } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import PropTypes from 'prop-types';

import { HttpCode } from '#/utils/contacts.js';
import { TRDefault, TRTooltip } from '@/components';
import { equipmentIndex } from '@/services/businessAnalysis';
import { BarCharts, TableTag } from '../../components';
import { handleEQUIPMENTTITLE } from './helper';
import styles from './index.less';

const ItemRender = (props) => {
  const { col, title, keys, data, columns, tripTotal, tripTotalRate, unitText = '', block } = props;

  useEffect(() => {
    initToolTip();
  }, []);

  const __echarts_ = useRef();
  const __tooltip_ = useRef([]);
  const getRef = (dom) => {
    __tooltip_.current.push(dom);
  };

  const _onToopFormatter = (params, item, index) => {
    if (item.tables) {
      const dataIndex = params[0].dataIndex;
      let timer = item.tables[dataIndex + 1].centerName;

      let array = [
        {
          name: '本期',
          value: `${item.tables[dataIndex + 1].thisPeriod}${unitText}`,
          color: '#9BE99E',
        },
        {
          name: '同期',
          value: `${item.tables[dataIndex + 1].theSamePeriod}${unitText}`,
          color: '#13C2C2',
        },
      ];
      __tooltip_.current[index] && __tooltip_.current[index].show(timer, array);
    }
  };

  const initToolTip = () => {
    data.map((item, index) => {
      if (item.tables) {
        const tables = item.tables;
        let timer = '合计';
        let array = [
          { name: '本期', value: `${tables[0].thisPeriod}${unitText}`, color: '#9BE99E' },
          { name: '同期', value: `${tables[0].theSamePeriod}${unitText}`, color: '#13C2C2' },
        ];
        __tooltip_.current[index] && __tooltip_.current[index].show(timer, array);
      }
    });
  };

  return (
    <div className={styles.box} style={{ flex: 1 }}>
      <div className={styles.boxWrap}>
        <span className={styles.boxTitle}>{title}</span>
        <div className={styles.head}>
          <span className={styles.num}>
            {keys == 'tripBody' ? tripTotal : data[0].frequencyOfFailure || 0}
          </span>
          {keys == 'tripBody' ? (
            <span className={styles.tag}>
              跳闸率<span style={{ paddingLeft: 4 }}>{tripTotalRate}</span>%
            </span>
          ) : (
            <TableTag
              isUp={data[0].rate > 0 ? true : false}
              value={data[0].rate}
              percentage={false}
              backgroundToColor={block}
            />
          )}
        </div>
      </div>
      {/* {*/}
      <Row className={styles.rowWrap}>
        {!!data.length &&
          data.map((item, index) => {
            const xData = [],
              thisPeriod = [],
              theSamePeriod = [];
            item.histogramBody &&
              item.histogramBody.dataList &&
              item.histogramBody.dataList.map((item) => {
                xData.push(item.centerName);
                thisPeriod.push(item.thisPeriod);
                theSamePeriod.push(item.theSamePeriod);
              });

            return (
              <Col
                key={`${keys}${index}`}
                style={col == 2 ? { padding: '0 18px', width: '50%' } : { padding: '0 18px' }}
                flex={col == 2 ? '' : 1}
              >
                <span className={styles.colHead}>
                  {data.length === 2 && <span>{item.switchType}</span>}
                </span>
                <div>
                  {!!xData.length && (
                    <>
                      <div className={styles.colDiv}>
                        <TRTooltip ref={getRef} key={index} suffixText="" />
                      </div>
                      <BarCharts
                        echartRef={__echarts_}
                        objStyle={{ height: 182 }}
                        xData={xData}
                        legend={{ show: false }}
                        initToolTipFn={initToolTip}
                        maxNum={Math.max.apply(null, [...thisPeriod, ...theSamePeriod])}
                        tooltip={{
                          trigger: 'axis',
                          extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1)',
                          backgroundColor: 'rgba(255, 255, 255, 1)',
                          textStyle: {
                            color: '#888E95',
                            borderWidth: 1,
                            borderColor: '#1A253C4B',
                            padding: 12,
                          },
                          axisPointer: {
                            type: 'cross',
                            label: {
                              backgroundColor: block ? '#161a1d' : '#F5F8FA',
                              color: block ? '#fff' : '#888E95',
                              shadowBlur: 0,
                            },
                          },
                          formatter: (params) => {
                            _onToopFormatter(params, item, index);
                          },
                        }}
                        block={block}
                        series={[
                          {
                            name: '本期',
                            type: 'bar',
                            itemStyle: {
                              normal: { color: '#9BE99E', barBorderRadius: [20, 20, 0, 0] },
                            },
                            data: thisPeriod,
                            barWidth: 8,
                            barGap: '80%',
                            markLine: {
                              data: [{ type: 'average', name: '平均值' }],
                              symbol: ['none', 'none'],
                              position: 'insideTopCenter',
                              silent: true,
                              itemStyle: {
                                normal: {
                                  lineStyle: {
                                    type: 'dotted',
                                    color: '#9BE99E',
                                  },
                                  label: {
                                    show: true,
                                    position: 'end',
                                    formatter: '平均',
                                    color: '#888E95',
                                  },
                                },
                              },
                              large: true,
                            },
                          },
                          {
                            name: '同期',
                            type: 'bar',
                            itemStyle: {
                              normal: {
                                color: '#13C2C2',
                                barBorderRadius: [20, 20, 0, 0],
                              },
                            },
                            data: theSamePeriod,
                            barWidth: 8,
                          },
                        ]}
                      />
                    </>
                  )}

                  <Table
                    rowKey="centerName"
                    locale={tableLocale}
                    columns={columns[index]}
                    dataSource={item.tables}
                    pagination={false}
                    style={{ width: '100%' }}
                  />
                </div>
              </Col>
            );
          })}
      </Row>
      {/* )} */}
    </div>
  );
};

ItemRender.propTypes = {
  col: PropTypes.number,
  title: PropTypes.string,
  keys: PropTypes.string,
  data: PropTypes.array,
  columns: PropTypes.array,
  tripTotal: PropTypes.number,
  tripTotalRate: PropTypes.node,
  unitText: PropTypes.string,
};

const EquipmentIndex = ({ params }) => {
  const [dataObj, setDataObj] = useState({});
  const [loading, setLoading] = useState(true);
  const { startDate, endDate, type, block } = params;

  useEffect(() => {
    equipmentAsync();
  }, [startDate, endDate, type]);

  const equipmentAsync = async () => {
    setLoading(true);
    setDataObj({});
    const response = await equipmentIndex({ ...params });

    if (response && response.statusCode == HttpCode.SUCCESS) {
      setLoading(false);
      const { tripBody, mttrBody, fanFaultBody } = response;
      if (tripBody && mttrBody && fanFaultBody) {
        setDataObj({ tripBody, mttrBody, fanFaultBody });
      }
    } else {
      // alert(response.message);
    }
  };

  return (
    <Spin spinning={loading}>
      <div className={`${styles.equipment} ${block ? styles.equipmentBlock : ''}`}>
        <div className={styles.title}>设备指标</div>
        {Object.keys(dataObj).length > 0 ? (
          <Row className={styles.rowContainer} style={{ flexWrap: 'nowrap' }}>
            {!!Object.keys(dataObj) &&
              Object.entries(handleEQUIPMENTTITLE(block)).map(([key, item]) => (
                <Col
                  key={key}
                  style={item.col == 2 ? { flex: 1 } : { width: '24.3%', marginLeft: '16px' }}
                >
                  {key === 'tripBody' ? (
                    <span>
                      {dataObj[key].tripDetailedBodies.length > 0 && (
                        <ItemRender
                          keys={key}
                          data={dataObj[key].tripDetailedBodies}
                          tripTotal={dataObj[key].tripTotal}
                          tripTotalRate={dataObj[key].tripTotalRate}
                          block={block}
                          {...item}
                        />
                      )}
                    </span>
                  ) : (
                    <ItemRender keys={key} data={[dataObj[key]]} {...item} block={block} />
                  )}
                </Col>
              ))}
          </Row>
        ) : (
          <div className={styles.empty}>
            <TRDefault type="emptysm" />
          </div>
        )}
      </div>
    </Spin>
  );
};

EquipmentIndex.propTypes = {
  params: PropTypes.object,
};

export default EquipmentIndex;
